package com.yuke.cloud.service.omc.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillDto;
import com.yuke.cloud.service.api.cmc.dto.CmsSecKillSkuDto;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.omc.dto.DmsStoreOrderApi;
import com.yuke.cloud.service.api.omc.dto.OdsOrderApiDto;
import com.yuke.cloud.service.api.omc.dto.StoreOrderDto;
import com.yuke.cloud.service.api.omc.exceptions.OmcBizException;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecApiDto;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.wmc.dto.WarehouseInfoDto;
import com.yuke.cloud.service.api.wmc.dto.WmsGiftDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.omc.config.Quartz;
import com.yuke.cloud.service.omc.controller.frontend.OdsPointsController;
import com.yuke.cloud.service.omc.dao.OdsOrderGoodsMapper;
import com.yuke.cloud.service.omc.dao.OdsOrderMapper;
import com.yuke.cloud.service.omc.dao.OdsShopCartMapper;
import com.yuke.cloud.service.omc.dto.*;
import com.yuke.cloud.service.omc.entity.OdsOrder;
import com.yuke.cloud.service.omc.entity.OdsOrderGoods;
import com.yuke.cloud.service.omc.entity.OdsPoints;
import com.yuke.cloud.service.omc.entity.OdsShopCart;
import com.yuke.cloud.service.omc.redis.RedisCacheTemplate;
import com.yuke.cloud.service.omc.service.OdsAwardRecordService;
import com.yuke.cloud.service.omc.service.OdsCommissionService;
import com.yuke.cloud.service.omc.service.OdsOrderService;
import com.yuke.cloud.service.omc.service.OdsPointsService;
import com.yuke.cloud.service.omc.utils.SequenceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * Created by ssx on 2018/09/03.
 */
@Service
@Transactional
@Slf4j
public class OdsOrderServiceImpl extends BaseService<OdsOrder> implements OdsOrderService {
    @Resource
    private OdsOrderMapper odsOrderMapper;
    @Resource
    private OdsOrderGoodsMapper odsOrderGoodsMapper;
    @Resource
    private OdsAwardRecordService odsAwardRecordService;
    @Resource
    private OdsCommissionService odsCommissionService;
    @Resource
    private OdsPointsController odsPointsController;
    @Resource
    private OdsPointsService odsPointsService;
    // add by wg 20190329 增加用户向店铺下单前对库存的判断
    @Resource
    private SmcFeignApi smcFeignApi;

    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;

    @Resource
    private CmcFeignApi cmcFeignApi;

    @Value("${yuke.shop-rebate-rate}")
    private Double shopRebateRate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private OdsShopCartMapper odsShopCartMapper;

    @Autowired
    private RedisCacheTemplate redisCacheTemplate;

    @Resource
    private PmcFeignApi pmcFeignApi;

    private static final String  SERIAL_NUM= "redis:serialNumber:";


    @Override
    public Map<String, String> haveShopStockCount(List<Map<String, String>> listSpecs) {
        Map<String, String> map = new HashMap();
        map.put("yes", "yes");

        for (Map<String, String> mapList : listSpecs) {
            Integer count = 0;
            Integer num = Integer.valueOf(mapList.get("number"));
            Long spcId = Long.valueOf(mapList.get("prod_spec"));
            Long shopId = Long.valueOf(mapList.get("shopid"));

            count = smcFeignApi.getShopStockCount(shopId, spcId);

            if (count - num < 0) {  // 库存不足
                // 获取店名
                String shopName = "店铺";
                List<Long> listShopIds = new ArrayList<>();
                listShopIds.add(shopId);
                System.out.println("oDS+++++++++odspayserviceImpl=++++++++listShopIds="+listShopIds);
                List<ShopInfoDto> shopInfoDtoList = smcFeignApi.getShopInfoByShopIds(listShopIds);
                if (shopInfoDtoList != null && shopInfoDtoList.size() > 0) {
                    shopName = shopInfoDtoList.get(0).getShopName();
                }
                map.put("no", shopName);
            }
        }

        return map;
    }

    //shopid和goodprice要和前台对应,num件数
    @Override
    public List<OdsOrderGoods> Creatord(Long orderId, List<Map<String, String>> listObjectFir, Long ueseid, Map receive, List<Map> transprice1, String shippingType, List<Map<String, String>> listPostscript) {

        // add by wg 20190328 如果订单重新提交，则只更新订单表，不用新生成订单
        OdsOrder odsOrder = null;
        if (orderId != null) {  // 对于已经提交的订单重新支付，只需更新一下订单信息，重新支付，地址、运费及留言可以修改
            // 先查询订单是否存在
            odsOrder = this.findById(Long.valueOf(orderId.toString()));
        }
        //收货地址
        String province = receive.get("province").toString();
        String name = receive.get("name").toString();
        String phone = receive.get("phone").toString();
        String city = receive.get("city").toString();
        String county = receive.get("county").toString();
        String dedail = receive.get("dedail").toString();

        //保存订单集合
        List<OdsOrder> ords = new ArrayList<OdsOrder>();
        Set<String> set = new HashSet<String>();
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (Map<String, String> mapList : listObjectFir) {
            for (Map.Entry entry : mapList.entrySet()) {
                set.add(String.valueOf(entry.getValue()));
            }
        }

//价格集合
        List<Integer> price6 = new ArrayList<Integer>();
//重量集合
        List<String> weights = new ArrayList<String>();
//数量
        List<Integer> num6 = new ArrayList<Integer>();
//商店id集合
        List<String> shop = new ArrayList<String>();
//商品规格id集合
        List<String> things = new ArrayList<String>();
        for (Map<String, String> mapList : listObjectFir) {
            for (Map.Entry entry : mapList.entrySet()) {
                for (String str : set) {
                    if (str.equals(entry.getValue())) {
                        //每个具体商品的总价格
                        int price = Integer.valueOf(mapList.get("product_price_total"));
                        //每个具体商品的数量
                        int num = Integer.valueOf(mapList.get("number"));
                        String spid = mapList.get("prod_spec");
                        String shopid = mapList.get("shopid");
                        String weight = mapList.get("weight");
                        price6.add(price);
                        shop.add(shopid);
                        num6.add(num);
                        weights.add(weight);
                        things.add(spid);
                    }
                }
                break;
            }
        }
        //先生成订单，再生成订单详情，要根据订单id生成订单详情ID
        List shopreal = new ArrayList();
        for (int i = 0; i < shop.size(); i++) {
            if (!shopreal.contains(shop.get(i))) {
                shopreal.add(shop.get(i));
            }
        }
        //生成订单的id可以查询到订单的id
        List li = new ArrayList();
        String postscript = "";
        for (int i = 0; i < shopreal.size(); i++) {
            int jiage = 0;

            OdsOrder order = new OdsOrder();
            if (odsOrder == null) {
                //雪花算法生成订单id，订单号用日期拼接
                long orderid = super.generateId();
                li.add(orderid);
                order.setOrderId(orderid);
                //20位长度的字符串
                UUID id = UUID.randomUUID();
                String[] idd = id.toString().split("-");
                String uuid20 = idd[0] + idd[1] + idd[2] + idd[3];
                //12位长度,相加一共生成32位的订单号
                String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
                String key = SERIAL_NUM + currentDate;
                long incr = redisCacheTemplate.incr(key, 1, 86400);
                //移位运算符<<，左移几位相当于乘以2的几次方, 1 << 2 = 4
                String code = SequenceUtils.getSequence(incr, 1 << 2);
                odsOrder.setOrderSn(uuid20 + currentDate + code);

                order.setUserId(ueseid);
                order.setOrderType((byte) 1);
                order.setShopId(Long.parseLong(shopreal.get(i).toString()));

                order.setCreateTime(new Date());
            } else {
                order.setShopId(odsOrder.getShopId());
                order.setOrderId(odsOrder.getOrderId());
            }

            for (int y = 0; y < shop.size(); y++) {
                if (shop.get(y).equals(shopreal.get(i).toString())) {
                    jiage += price6.get(y) * num6.get(y);
                    // del by wg 20190402 用户留言单独从一个json对象中传过来
//                    if (listObjectFir.get(y).get("postscript")!=null&&!listObjectFir.get(y).get("postscript").equals("")) {
//                        postscript = listObjectFir.get(y).get("postscript");
//                    }
                }
            }
            for (int i1 = 0; i1 < transprice1.size(); i1++) {
                if (order.getShopId().toString().equals(transprice1.get(i1).get("shopid").toString())) {
                    double price = Double.parseDouble(transprice1.get(i1).get("price").toString());
                    order.setFreightPayable((int)(price)); //*100));
                }
            }
            order.setPostscript(postscript);
            order.setAmountPayable(jiage);
            order.setShippingStatus((byte) 0);
            order.setConsignee(name);
            order.setTelephone(phone);
            order.setRegionProvinceId(Long.valueOf(province));
            order.setRegionCityId(Long.valueOf(city));
            order.setRegionCountyId(Long.valueOf(county));
            order.setAddress(dedail);
            order.setExpressId(Long.valueOf("1"));
            order.setOrderStatus((byte) 0);
            order.setPayStatus((byte) 0);

            order.setShippingType(Byte.valueOf(shippingType));

            // add by wg 20190402 增加postscript
            if (PublicUtil.isNotEmpty(listPostscript)) {
                for (Map<String, String> mapList : listPostscript) {
                    if (order.getShopId().toString().equals(mapList.get("shopid"))) {
                        if (PublicUtil.isNotEmpty(mapList.get("postscript"))) {
                            order.setPostscript(mapList.get("postscript"));
                        }
                        break;
                    }
                }
            }
            //保存到数据库
            if (odsOrder == null) {
                super.save(order);
            } else {
                super.update(order);
                return null;
            }
        }
        for (int i = 0; i < li.size(); i++) {
            OdsOrder od = new OdsOrder();
            od.setOrderId(Long.valueOf(li.get(i).toString()));
            OdsOrder order = super.selectOne(od);
            ords.add(order);
        }
        //暂时没有添加物流，仓库，商品属性等信息，
        List<OdsOrderGoods> goodsods = new ArrayList<OdsOrderGoods>();
        //生成订单详情表
        for (int i = 0; i < num6.size(); i++) {
            OdsOrderGoods goods = new OdsOrderGoods();
            long id = 0;
            for (int y = 0; y < ords.size(); y++) {
                if (ords.get(y).getShopId().toString().equals(shop.get(i))) {
                    id = Long.valueOf(ords.get(y).getOrderId());
                    break;
                }
            }
            goods.setOrderId(id);
            goods.setSpecId(Long.parseLong(things.get(i)));
            goods.setGoodsWeight(Integer.valueOf(weights.get(i)));
            goods.setGoodsPrice(price6.get(i));
            goods.setGoodsNum(num6.get(i));
            goods.setPayPrice(price6.get(i));  // add by wg 20190322
            //商品重量，商品属性可以根据商品id查询商品规格
            goods.setGoodsStatus((byte) 0);
            //保存到数据库
            goodsods.add(goods);
        }
        return goodsods;
    }

    @Override
    public List<OdsOrder> findbystatus(OdsOrder ods) {

        // mod by wg 20190404 按照时间倒序排
        Example example = new Example(OdsOrder.class);
        example.setOrderByClause("create_time desc");
        Example.Criteria criteria = example.createCriteria();
        if (ods.getShippingStatus() != null) {
            criteria.andEqualTo("shippingStatus", ods.getShippingStatus());
        }

        if (ods.getUserId() != null) {
            criteria.andEqualTo("userId", ods.getUserId());
        }

        if (ods.getOrderType() != null) {
            criteria.andEqualTo("orderType", ods.getOrderType());
        }

        if (ods.getOrderStatus() != null) {
            criteria.andEqualTo("orderStatus", ods.getOrderStatus());
        }

        if (ods.getPayStatus() != null) {
            criteria.andEqualTo("payStatus", ods.getPayStatus());
        }

        if (ods.getShopId() != null) {
            criteria.andEqualTo("shopId", ods.getShopId());
        }

        if (ods.getShippingType() != null) {
            criteria.andEqualTo("shippingType", ods.getShippingType());
        }

        if (ods.getFactoryShopId() != null) {
            criteria.andEqualTo("factoryShopId", ods.getFactoryShopId());
        }

        if (ods.getPayType() != null) {
            criteria.andNotEqualTo("payType", ods.getPayType());
        }

        List<OdsOrder> orderslist = odsOrderMapper.selectByExample(example);

        return orderslist;
    }

    //商户向平台下单
    @Override
    public List<OdsOrderGoods> createoderbyshop(List<Map<String, String>> listObjectFir, Long ueseid, Object price, Long shopid, String type, Map receivemap, String shippingType, String postscript) {
        //需要店铺id
        OdsOrder odsOrder = new OdsOrder();
        //20位长度的字符串
        UUID id = UUID.randomUUID();
        String[] idd = id.toString().split("-");
        String uuid20 = idd[0] + idd[1] + idd[2] + idd[3];
        //12位长度,相加一共生成32位的订单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYYMMddHHmm");
        String format = simpleDateFormat.format(new Date());
        long orderid = super.generateId();
        odsOrder.setOrderId(orderid);
        odsOrder.setOrderType((byte)2);
        odsOrder.setOrderSn(uuid20 + format);
        if (type.equals(2)) {
            //2店铺下单调拨，不发货
            //odsOrder.setOrderType((byte) 2);
        } else if (type.equals("0")) {
            //0店铺下单买东西，发货
            odsOrder.setConsignee(receivemap.get("name").toString());
            odsOrder.setTelephone(receivemap.get("phone").toString());
            odsOrder.setRegionCityId(Long.valueOf(receivemap.get("city").toString()));
            odsOrder.setRegionCountyId(Long.valueOf(receivemap.get("county").toString()));
            odsOrder.setRegionProvinceId(Long.valueOf(receivemap.get("province").toString()));
            odsOrder.setAddress(receivemap.get("detail").toString());
            odsOrder.setOrderType((byte) 2);

            odsOrder.setShippingType(Byte.valueOf(shippingType));
        }
        odsOrder.setUserId(ueseid);
        odsOrder.setExpressId(Long.valueOf("1"));
        odsOrder.setShopId(shopid);
        odsOrder.setPayStatus((byte) 0);
        odsOrder.setCreateTime(new Date());
        double v = Double.parseDouble(price.toString()); //*100;
        odsOrder.setAmountPayable((int)v);

        // add by wg 20190402 增加线下单用户留言信息
        if (PublicUtil.isNotEmpty(postscript)) {
            odsOrder.setPostscript(postscript);
        }

        super.save(odsOrder);
        Long orderId = odsOrder.getOrderId();
        List<OdsOrderGoods> list = new ArrayList<OdsOrderGoods>();
        for (int i = 0; i < listObjectFir.size(); i++) {
            OdsOrderGoods odsOrderGoods = new OdsOrderGoods();
            odsOrderGoods.setOrderId(orderId);
            odsOrderGoods.setSpecId(Long.valueOf(listObjectFir.get(i).get("prod_spec")));
            double v1 = Double.parseDouble(listObjectFir.get(i).get("product_price_total")); //*100;
            odsOrderGoods.setPayPrice((int)v1);
            odsOrderGoods.setGoodsPrice((int)v1); // add by wg 20190322
            odsOrderGoods.setGoodsNum(Integer.valueOf(listObjectFir.get(i).get("number")));
            odsOrderGoods.setGoodsWeight(Integer.valueOf(listObjectFir.get(i).get("weight")));
            list.add(odsOrderGoods);
        }
        return list;
    }

    @Override
    public List<OdsOrder> countsales(Date begintime, Date endtinme, Long shopid) {
        return odsOrderMapper.countsales(begintime, endtinme, shopid);

    }

    @Override
    public List<Map<String, Object>> countsalesbyquarter(Date begintime, Date endtinme, Long longshopid) {
        return odsOrderMapper.countsalesbyquarter(begintime, endtinme, longshopid);

    }

    @Override
    public List<Map<String, Object>> countsalesbymonth(Date begintime, Date endtinme, Long longshopid) {
        return odsOrderMapper.countsalesbymonth(begintime, endtinme, longshopid);

    }

    @Override
    public List<Map<String, Object>> countAmountPayableByMonth(Date begintime, Date endtinme, Long longshopid) {
        return odsOrderMapper.countAmountPayableByMonth(begintime, endtinme, longshopid);

    }

    @Override
    public List<Map<String, Object>> countsalesbyday(Date begintime, Date endtinme, Long longshopid) {
        return odsOrderMapper.countsalesbyday(begintime, endtinme, longshopid);

    }

    @Override
    public List<Map<String, Object>> countProductsalesbytime(Date begintime, Date endtinme, Long longshopid, Object productid, String bywhat) {
        List<Map<String, Object>> ids = null;
        List<Map<String, Object>> mapfinal = new ArrayList<Map<String, Object>>();
        //按季分类
        if (bywhat.trim().equals("quarter")) {
            ids = odsOrderMapper.selectidbyquarter(begintime, endtinme, longshopid);
            ids = getodsordergoodsbyidandproductid(ids, productid);
            Set<String> set = new HashSet<String>();
            for (int i = 0; i < ids.size(); i++) {
                set.add(ids.get(i).get("YEAR(create_time)") + "" + ids.get(i).get("QUARTER(create_time)"));
            }
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String time = iterator.next().toString();
                Map<String, Object> map2 = new HashMap<String, Object>();
                int money = 0;
                for (int i = 0; i < ids.size(); i++) {
                    if ((ids.get(i).get("YEAR(create_time)").toString() + ids.get(i).get("QUARTER(create_time)").toString()).equals(time)) {
                        money += Integer.valueOf(ids.get(i).get("money").toString());
                    }
                }
                map2.put("money", money);
                map2.put("time", time);
                mapfinal.add(map2);
            }
            }
        //按月分类
        if (bywhat.trim().equals("month")) {
            ids = odsOrderMapper.selectidbymonth(begintime, endtinme, longshopid);
            ids = getodsordergoodsbyidandproductid(ids, productid);
            Set<String> set = new HashSet<String>();
            for (int i = 0; i < ids.size(); i++) {
                set.add(ids.get(i).get("YEAR(create_time)") + "" + formatit(ids.get(i).get("MONTH(create_time)")));
            }
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String time = iterator.next().toString();
                Map<String, Object> map2 = new HashMap<String, Object>();
                int money = 0;
                for (int i = 0; i < ids.size(); i++) {
                    if ((ids.get(i).get("YEAR(create_time)").toString() + formatit(ids.get(i).get("MONTH(create_time)"))).equals(time)) {
                        money += Integer.valueOf(ids.get(i).get("money").toString());
                    }
                }
                map2.put("money", money);
                map2.put("time", time);
                mapfinal.add(map2);
            }


        }
//按照周分类
        if (bywhat.trim().equals("week")) {
            ids = odsOrderMapper.selectidbyweek(begintime, endtinme, longshopid);
            ids = getodsordergoodsbyidandproductid(ids, productid);
            Set<String> set = new HashSet<String>();
            for (int i = 0; i < ids.size(); i++) {
                set.add(ids.get(i).get("YEAR(create_time)") + "" + formatit(ids.get(i).get("MONTH(create_time)")) + "" + formatit(ids.get(i).get("WEEK(create_time)")));
            }

            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String time = iterator.next().toString();
                Map<String, Object> map2 = new HashMap<String, Object>();
                int money = 0;
                for (int i = 0; i < ids.size(); i++) {
                    if ((ids.get(i).get("YEAR(create_time)").toString() + formatit(ids.get(i).get("MONTH(create_time)").toString()) + formatit(ids.get(i).get("WEEK(create_time)"))).equals(time)) {
                        money += Integer.valueOf(ids.get(i).get("money").toString());
                    }
                }
                map2.put("money", money);
                map2.put("time", time);
                mapfinal.add(map2);
            }
        }

        //按照天分类
        if (bywhat.trim().equals("day")) {
            ids = odsOrderMapper.selectidbyday(begintime, endtinme, longshopid);
            ids = getodsordergoodsbyidandproductid(ids, productid);
            Set<String> set = new HashSet<String>();
            for (int i = 0; i < ids.size(); i++) {
                set.add(ids.get(i).get("YEAR(create_time)") + "" + formatit(ids.get(i).get("MONTH(create_time)")) + "" + formatit(ids.get(i).get("DAY(create_time)")));
            }
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                String time = iterator.next().toString();
                Map<String, Object> map2 = new HashMap<String, Object>();
                int money = 0;
                for (int i = 0; i < ids.size(); i++) {
                    if ((ids.get(i).get("YEAR(create_time)").toString() + formatit(ids.get(i).get("MONTH(create_time)")) + formatit(ids.get(i).get("DAY(create_time)"))).equals(time)) {
                        money += Integer.valueOf(ids.get(i).get("money").toString());
                    }
                }
                map2.put("money", money);
                map2.put("time", time);
                mapfinal.add(map2);
            }
        }

        return mapfinal;

    }

    @Override
    public List<OdsOrder> transferEveryday(Integer day) {
        List<OdsOrder> maps = odsOrderMapper.transferEveryday(day);
        return maps;
    }

    @Override
    public long getsnowid() {
        return super.generateId();

    }

    @Override
    public Integer batchupdate(List<OdsOrder> odsOrders) {
        return odsOrderMapper.batchupdate(odsOrders);
    }

    @Override
    public List<Map> recommond01(List<Long> specIds) {
        return odsOrderGoodsMapper.recommond01(specIds);
    }

    @Override
    public List<Map> recommond02(List<Long> order_id) {
        return odsOrderMapper.recommond02(order_id);
    }

    @Override
    public List<Map> countsalebyweek(Long shopid) {

        return odsOrderMapper.countsalesbyweek(shopid);
    }

    @Override
    public List<Map> countsalesbytime(Date begintime, Date endtinme, Long shopid) {
        return odsOrderMapper.countsalesbytime(begintime, endtinme, shopid);
    }

    @Override
    public List<Map> countnumbytime(Date begintime, Date endtinme, Long shopid) {
        return odsOrderMapper.countnumbytime(begintime, endtinme, shopid);
    }

    @Override
    public List<Map> getgoods(List<Long> list1) {
        List<Map> getgoods = odsOrderMapper.getgoods(list1);
        return getgoods;
    }

    @Override
    public List<Map> getfinish() {

        return odsOrderMapper.getfinish();
    }

    @Override
    public Map selectaddressbyid(Long id) {
        return odsOrderMapper.selectaddressbyid(id);
    }

    private Object formatit(Object o) {
        byte[] bytes = o.toString().getBytes();
        if (bytes.length == 1) {
            return "0" + o;
        }
        return o;
    }


    private List<Map<String, Object>> getodsordergoodsbyidandproductid(List<Map<String, Object>> ids, Object productid) {
        for (int i = 0; i < ids.size(); i++) {
            Long aLong = Long.valueOf(ids.get(i).get("order_id").toString());
            Object productprice = odsOrderGoodsMapper.selectbyorderidanbyproductid(aLong, Long.valueOf(productid.toString()));
            Map<String, Object> map = ids.get(i);
            if (productprice == null) {
                map.put("money", 0);
            } else {
                map.put("money", productprice);
            }

        }
        return ids;
    }


    @Override
    public void deleteById(Long id) {
        super.deleteById(id);
    }

    @Override
    public OdsOrder findById(Long id) {
        return super.findById(id);

    }

    public List<OdsOrder> findAll() {
        return super.findAll();
    }

    public Date gettime() {
        //获取无意义填充时间
        //未付款和未发货的时候,统一设置时间为
        String time = "1970-10-10 10-10-10";
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date date = new Date();
        String format = sf.format(date);
        Date parse = null;
        try {
            parse = sf.parse(format);
        } catch (ParseException e) {
            System.out.println("失败");
            e.printStackTrace();
        }
        return parse;
    }

    /**
     * 统计指定店铺已获得的返利总额
     * @param shopId
     * @return
     */
    @Override
    public Integer getAlrdyAmountCheckout(Long shopId) {
        Integer alrdyAmountCheckout = odsOrderMapper.selectAlrdyAmountCheckout(shopId);
        return alrdyAmountCheckout;
    }
    /**
     * 统计指定店铺已获得的返点总额
     * @param shopId
     * @return
     */
    @Override
    public Integer getAlrdyAmountDiscount(Date begintime,Date endtime,Long shopId) {
        Integer alrdyAmountDiscount = 0;
        List<Map<String, Object>> discountTemp =odsOrderMapper.selectAlrdyAmountDiscount(begintime,endtime,shopId);

        // 扣除退货或退款部分
        if (discountTemp != null && discountTemp.size() > 0) {
            alrdyAmountDiscount = Math.round( Integer.parseInt(discountTemp.get(0).get("SUM(discount)").toString()));// 总金额
        }
        return alrdyAmountDiscount;
    }
    /**
     * 统计指定店铺预估当月的返利总额
     * 给用户返利的订单只要已完成的就直接返利，不考虑订单是否还可能退款
     * @param shopId
     * @return
     */
    @Override
    public Integer getPreAmountCheckout(Long shopId) {

        Integer preAmountCheckout = 0;

        // 先获取店铺有返利的订单
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("shopId", shopId);
        criteria.andEqualTo("orderType", 2);  // 店铺线下进货
        criteria.andEqualTo("isCheckout", 0); // 没有返利
        criteria.andEqualTo("payStatus", 1);  // 已支付
        List<OdsOrder> listCheckoutOrderTemp = odsOrderMapper.selectByExample(example);

        // 扣除退货或退款部分
        if (listCheckoutOrderTemp != null && listCheckoutOrderTemp.size() > 0) {
            for (OdsOrder odsOrder : listCheckoutOrderTemp) {
                if (odsOrder.getOrderStatus() == 4 || odsOrder.getOrderStatus() == 5) {  // 已退货或部分退货
                    Integer refundMoney = wmcStorageFeignApi.getrefundamound(odsOrder.getOrderId());
                    if (refundMoney == null) {
                        continue;
                    }

                    preAmountCheckout += (int)Math.round((odsOrder.getAmountPaid() - refundMoney - odsOrder.getFreightPayable()) * shopRebateRate);  // 转账总额-已退款部分-运费为进货总价
                } else if (odsOrder.getOrderStatus() == 2) {  // 正常完成订单
                    boolean flag = wmcStorageFeignApi.ifexits(odsOrder.getOrderId());
                    if (!flag) {
                        preAmountCheckout += (int)Math.round((odsOrder.getAmountPaid() - odsOrder.getFreightPayable()) * shopRebateRate);  // 转账总额-已退款部分-运费为进货总价
                    }
                }
            }
        }

        return preAmountCheckout;
    }

    /**
     * 统计指定店铺实际当月的总额
     * 查看当月金额
     * @param shopId
     * @return
     */
    @Override
    public Integer getDoAmountMoney(Date begintime,Date endtime,Long shopId) {

        Integer doAmountMoney = 0;


        List<Map<String, Object>> listCheckoutOrderTemp = odsOrderMapper.countsalesbymonth(begintime,endtime,shopId);

        // 扣除退货或退款部分
        if (listCheckoutOrderTemp != null && listCheckoutOrderTemp.size() > 0) {
            doAmountMoney = Math.round( Integer.parseInt(listCheckoutOrderTemp.get(0).get("SUM(amount_payable)").toString()));// 总金额
        }

        return doAmountMoney;
    }
    /**
     * 统计指定店铺实际当月的返利总额
     * 查看当月实际已返利金额
     * @param shopId
     * @return
     */
    @Override
    public Integer getDoAmountCheckout(Date begintime,Date endtime,Long shopId) {

        Integer doAmountCheckout = 0;
        Integer doAmountMoney = 0;
        List<Map<String, Object>> listCheckoutOrderTemp = odsOrderMapper.countsalesbymonth(begintime,endtime,shopId);

        // 扣除退货或退款部分
        if (listCheckoutOrderTemp != null && listCheckoutOrderTemp.size() > 0) {
            doAmountMoney = Math.round( Integer.parseInt(listCheckoutOrderTemp.get(0).get("SUM(amount_payable)").toString()));// 总金额
        }
        Long groupId = 220839532667469824L;
        Wrapper wrap = wmcStorageFeignApi.getGroupIdByShopId(shopId);
        if (wrap.getCode() == 200 && wrap.getResult() != null ){
            groupId = Long.valueOf(wrap.getResult().toString());
        }

        Map<String,String> map = odsCommissionService.getMonthRebate(groupId);

        //2如果返回为空，或活动未开启，
        if(map == null){
            return 0;
        }

        double reachFirstMoney = (double) Integer.valueOf(map.get("reachFirstMoney"));
        double returnFirstRate =  Double.parseDouble(map.get("returnFirstRate"));
        double reachSecondMoney = (double) Integer.valueOf(map.get("reachSecondMoney"));
        double returnSecondRate = Double.parseDouble(map.get("returnSecondRate"));
        // 扣除退货或退款部分



       if (Double.doubleToLongBits(doAmountMoney) >Double.doubleToLongBits(reachSecondMoney)){
           //6保存返利信息
           doAmountCheckout = Integer.valueOf(String.valueOf(Math.round(doAmountMoney*returnSecondRate)));

       }else if (Double.doubleToLongBits(doAmountMoney) >Double.doubleToLongBits(reachFirstMoney)){
           //6保存返利信息
           doAmountCheckout = Integer.valueOf(String.valueOf(Math.round(doAmountMoney*returnFirstRate)));

       }





        return doAmountCheckout;
    }
    /**
     * 获取需要返利转账的数据
     * @return
     */
    @Override
    public List<Map<String, Object>> getRebateTransferData() {

        List<OdsOrder> listCheckoutOrder = new ArrayList<>();

        // 先获取店铺有返利的订单
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderType", 2);  // 店铺线下进货
        criteria.andEqualTo("isCheckout", 0); // 没有返利
        criteria.andEqualTo("payStatus", 1);  // 已支付
        List<OdsOrder> listCheckoutOrderTemp = odsOrderMapper.selectByExample(example);

        // 获取需要返利的订单及店铺信息
        List<Long> shopIds = new ArrayList<>();
        for (OdsOrder odsOrder : listCheckoutOrderTemp) {
            if (odsOrder.getOrderStatus() == 4 || odsOrder.getOrderStatus() == 5) {  // 已退货或部分退货
                Integer refundMoney = wmcStorageFeignApi.getrefundamound(odsOrder.getOrderId());
                if (refundMoney == null) {
                    continue;
                }
                //部分退款，需要转账，订单总金额-已退款部分为最终结算的款
                odsOrder.setRefundMoney(refundMoney);
                listCheckoutOrder.add(odsOrder);

                if (!shopIds.contains(odsOrder.getShopId())) {
                    shopIds.add(odsOrder.getShopId());
                }
            } else if (odsOrder.getOrderStatus() == 2) {  // 正常完成订单
                boolean flag = wmcStorageFeignApi.ifexits(odsOrder.getOrderId());
                if (!flag) {
                    //正常购买，不退款的
                    odsOrder.setRefundMoney(0);
                    listCheckoutOrder.add(odsOrder);

                    if (!shopIds.contains(odsOrder.getShopId())) {
                        shopIds.add(odsOrder.getShopId());
                    }
                }
            }
        }

        List<ShopInfoDto> shopAccountByShopIds = smcFeignApi.getShopAccountByShopIds(shopIds);
        if (shopAccountByShopIds == null||shopAccountByShopIds.size() == 0) {
            log.error("获取店铺账号失败！");
            return null;
        }

        Map mapData = null;
        List<Map<String, Object>> listTransferData = new ArrayList();
        for (int i = 0; i < shopAccountByShopIds.size(); i++) {
            int totalMoney = 0;

            JSONArray orderJsonArray = new JSONArray();
            mapData = new HashMap();
            for (int j = 0; j < listCheckoutOrder.size(); j++) {
                JSONObject orderJson = new JSONObject();
                if (listCheckoutOrder.get(j).getShopId().longValue() == shopAccountByShopIds.get(i).getShopId().longValue()) {
                    OdsOrder odsOrder = listCheckoutOrder.get(j);
                    Integer amountPaid = odsOrder.getAmountPaid();
                    Integer amountCheckout = 0;
                    if (odsOrder.getRefundMoney() != null) {
                        amountCheckout = (int)Math.round((amountPaid - odsOrder.getRefundMoney() - odsOrder.getFreightPayable()) * shopRebateRate);
                        orderJson.put("orderId", odsOrder.getOrderId());
                        orderJson.put("amountCheckout", amountCheckout);
                        orderJsonArray.add(orderJson);
                    } else {
                        amountCheckout = (int)Math.round((amountPaid - odsOrder.getFreightPayable()) * shopRebateRate);
                        orderJson.put("orderId", odsOrder.getOrderId());
                        orderJson.put("amountCheckout", amountCheckout);
                        orderJsonArray.add(orderJson);
                    }

                    totalMoney += amountCheckout;
                }
            }

            mapData.put("account_no", shopAccountByShopIds.get(i).getAccountNo());
            double v = ((double) totalMoney) / 100;
            double value = new BigDecimal(v).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            mapData.put("totalmoney", value);
            mapData.put("orderIds", orderJsonArray);
            mapData.put("orderType", 2);  //增加订单类型设定，值为店铺线下进货订单
            mapData.put("userId", shopAccountByShopIds.get(i).getUserId());
            listTransferData.add(mapData);
        }

        return listTransferData;
    }

    /**
     * 保存订单，返回订单ID集合及应支付的总额.订单的orderSn，在同一次提交的两个订单前28是一致的
     * @param orderInfoDto
     * @return
     */
    @Override
    public Map<String, String> saveOrder(OrderInfoDto orderInfoDto, List<CmsSecKillSkuDto> cmsSecKillSkuDtos, Boolean isUserOrder) {
        //订单收件人信息对象
        RecipientDto recipientDto = orderInfoDto.getRecipientDto();
        //订单基本信息集合
        List<OrderBasicDto> orderBasicDtos = orderInfoDto.getOrderBasicDtos();
        // 用于存放需要
        List<Map> listBookStock = new ArrayList<Map>();
        Map<String, String> mapResult = new HashMap<>();
        String strOrderIds = "";
        Integer totalPay = 0;

        //20位长度的字符串
        UUID id = UUID.randomUUID();
        String[] idd = id.toString().split("-");
        String uuid20 = idd[0] + idd[1] + idd[2] + idd[3];
        //12位长度,相加一共生成32位的订单号
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());

        //定义支付类型为（支付宝支付）
        Byte payType = 2;
        for (OrderBasicDto orderBasicDto : orderBasicDtos) {
            //获取订单Id
            Long orderId = orderBasicDto.getOrderId();

            OdsOrder odsOrder = null;
            // 如果订单重新提交，则只更新订单表，不用新生成订单
            if (PublicUtil.isNotEmpty(orderId) && orderId > 0L) {
                // 先查询订单是否存在
                odsOrder = this.findById(orderId);
            }

            if (odsOrder == null) {
                OdsOrder order = new OdsOrder();

                //类复制 忽略null值
                BeanUtil.copyProperties(orderBasicDto, order, CopyOptions.create().setIgnoreNullValue(true));
                order.setCouponReceiveId(orderInfoDto.getCouponReceiveId());
                order.setRedReceiveId(orderInfoDto.getRedReceiveId());
                //当支付类型为积分支付时
                if (order.getPayType().toString().equals("5") || order.getPayType().toString().equals("6") || order.getPayType().toString().equals("7")){
                    order.setDiscount(orderBasicDto.getPointBalance());
                }

                BeanUtil.copyProperties(recipientDto, order, CopyOptions.create().setIgnoreNullValue(true));
                //设置订单Id
                order.setOrderId(super.generateId());

                // 处理厂家直销订单
                if (orderBasicDto.getIsFactory()) {
                    // 获取厂家直销店铺信息
                    if (orderBasicDto.getFactoryId() == null) {
                        log.error("厂家直销订单没有厂家ID");
                        throw new OmcBizException(ErrorCodeEnum.GL99990100);
                    }

                    Wrapper<ShopInfoDto> wrapResult = smcFeignApi.getShopByFactoryId(orderBasicDto.getFactoryId());
                    if (wrapResult != null && wrapResult.getCode() == 200) {
                        ShopInfoDto shopInfoDto = wrapResult.getResult();
                        //设置厂家直销店铺Id
                        order.setFactoryShopId(shopInfoDto.getShopId());
                    } else {
                        log.error("无法获取到厂家直销店信息");
                        throw new OmcBizException(ErrorCodeEnum.GL99990002);
                    }
                }


                String key = SERIAL_NUM + currentDate;
                long incr = redisCacheTemplate.incr(key, 1, 86400);
                //移位运算符<<，左移几位相当于乘以2的几次方, 1 << 2 = 4
                String code = SequenceUtils.getSequence(incr, 1 << 2);

                order.setOrderSn(uuid20 + currentDate + code);



                order.setUserId(orderInfoDto.getUserId());
                //设置初始配送状况
                order.setShippingStatus((byte) 0);
                //配送方式
                if (order.getOrderType().equals((byte)2) && order.getShippingType().equals((byte)2)
                        && orderInfoDto.getRecipientDto().getDeliveryMethod() != null){
                    order.setDeliveryMethod(orderInfoDto.getRecipientDto().getDeliveryMethod());
                }
//                order.setOrderType((byte) 1);
//                order.setExpressId(Long.valueOf("1"));
                // add by wg 20190711 增加货到付款处理
                //若为货到付款、账户余额支付、积分支付
                if (order.getPayType().toString().equals("0") || order.getPayType().toString().equals("4")
                        || order.getPayType().toString().equals("5") || order.getPayType().toString().equals("8")
                        || order.getPayType().toString().equals("9")) {
                    //订单状态为已确认
                    order.setOrderStatus((byte) 1);
                } else {
                    //反之为 未确认 状态
                    order.setOrderStatus((byte) 0);
                }
                //初始支付状态为 未付款
                if (order.getPayType().toString().equals("4") || order.getPayType().toString().equals("5")
                        || order.getPayType().toString().equals("9")){
                    order.setPayStatus((byte) 1);
                }else{
                    order.setPayStatus((byte) 0);
                }

               //todo 如果提交的订单状态为已完成（2），保存订单状态为已完成（2）
                if (orderBasicDto.getOrderStatus() != null && orderBasicDto.getOrderStatus().toString().equals("2")){
                    order.setOrderStatus((byte)2);
                }
                //todo 下单时间为当前时间
                order.setCreateTime(orderBasicDto.getCreateTime() != null ? orderBasicDto.getCreateTime() : new Date());
                //todo     新订单保存到数据库
                super.save(order);

                //todo    新增订单后添加积分
                if (order.getPayType().toString().equals("0") || order.getPayType().toString().equals("2")
                        || order.getPayType().toString().equals("3") || order.getPayType().toString().equals("4") ) {
                    addOrderPoint(order);
                }

                //兑奖商品处理
                List<OrderGoodsDto> orderGoodsDtoList = odsAwardRecordService.getAwardRecordList(orderBasicDto);
                if (orderGoodsDtoList != null && orderGoodsDtoList.size() >0){
                    orderBasicDto.getOrderGoodsDtos().addAll(orderGoodsDtoList);
                }


                List<Long> listSpecId = new ArrayList<>();
                // 保存该订单下的商品信息
                List<OrderGoodsDto> orderGoodsDtos = orderBasicDto.getOrderGoodsDtos();
                for (OrderGoodsDto orderGoodsDto : orderGoodsDtos) {
                    //若商品数量等于0
                    if (orderGoodsDto.getGoodsNum().equals(0)){
                        //则终止本次循环
                        continue;
                    }
                    OdsOrderGoods odsOrderGoods = new OdsOrderGoods();

                    BeanUtil.copyProperties(orderGoodsDto, odsOrderGoods, CopyOptions.create().setIgnoreNullValue(true));
                    //设置订单Id
                    odsOrderGoods.setOrderId(order.getOrderId());
                    //设置 实付金额 为 商品销售价格 单位为分,老版没有传PayPrice，会报错
                    //odsOrderGoods.setPayPrice(orderGoodsDto.getPayPrice());
                    if (orderGoodsDto.getPayPrice() != null && orderGoodsDto.getPayPrice() > 0){
                        //把红包金额分摊到每个商品上,红包金额大于0，B端
                        if (orderBasicDto.getRedMoney() != null && orderBasicDto.getRedMoney() > 0){
                            float rate = (float)orderBasicDto.getRedMoney() / (orderBasicDto.getAmountPayable() + orderBasicDto.getRedMoney());
                            odsOrderGoods.setPayPrice(Math.round(orderGoodsDto.getPayPrice() * (1 - rate)));
                        }

                    }else{
                        odsOrderGoods.setPayPrice(orderGoodsDto.getGoodsPrice());
                    }

                    //设置初始发货状态为 未发货
                    if (orderGoodsDto.getGoodsStatus() != null){
                        odsOrderGoods.setGoodsStatus(orderGoodsDto.getGoodsStatus());
                    }else{
                        odsOrderGoods.setGoodsStatus((byte)0);
                    }

                    //若商品ProductId为空 则设置为0
                    if (PublicUtil.isEmpty(odsOrderGoods.getProductId())) {
                        odsOrderGoods.setProductId(0L);
                    }
                    //若商品属性为空  则设置为""
                    if (PublicUtil.isEmpty(odsOrderGoods.getGoodsAttribute())) {
                        odsOrderGoods.setGoodsAttribute("");
                    }
                    //若物流单Id 为空 则设置为0
                    if (PublicUtil.isEmpty(odsOrderGoods.getOrderDeliveryId())) {
                        odsOrderGoods.setOrderDeliveryId(0L);
                    }
                    //若发货仓库Id为空 则设置为0
                    if (PublicUtil.isEmpty(odsOrderGoods.getWarehouseId())) {
                        odsOrderGoods.setWarehouseId(0L);
                    }
                    //若商品重量为空 设置重量为0
                    if (PublicUtil.isEmpty(odsOrderGoods.getGoodsWeight())) {
                        odsOrderGoods.setGoodsWeight(0);
                    }
                    //todo   添加一条记录
                    odsOrderGoodsMapper.insert(odsOrderGoods);

                    Map mapGoods = new HashMap();
                    mapGoods.put("shopId", orderBasicDto.getShopId());
                    mapGoods.put("specId", orderGoodsDto.getSpecId());
                    mapGoods.put("goodsNum", orderGoodsDto.getGoodsNum());
                    mapGoods.put("orderId", order.getOrderId());
                    mapGoods.put("isFactory", orderBasicDto.getIsFactory());
                    mapGoods.put("warehouseId", orderBasicDto.getWarehouseId());  // add by wg 20190727
                    listBookStock.add(mapGoods);

                    listSpecId.add(orderGoodsDto.getSpecId());
                }//for orderGoodsDtos

                if (PublicUtil.isEmpty(strOrderIds)) {
                    strOrderIds = order.getOrderId().toString();
                } else {
                    strOrderIds += "," + order.getOrderId().toString();
                }
                //订单应该支付的金额，包含运费等，单位为分
                totalPay += order.getAmountPayable();

                // todo  成功生成订单后，清空购物车
                Example example = new Example(OdsShopCart.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId", orderInfoDto.getUserId());
                criteria.andEqualTo("cartType", orderBasicDto.getOrderType());
                criteria.andIn("specId", listSpecId);
                odsShopCartMapper.deleteByExample(example);
                //若支付类型为null
                // mod by wg 20190711
                if (order.getPayType() != null) {
                    payType = order.getPayType();
                } else {
                    payType = 2;
                }
                //odsOrder==null
            } else {
                //odsOrder!=null
                payType = orderBasicDto.getPayType();

                // add by wg 20190711 更新原有订单信息，但支付方式暂时不更新，待支付成功后再更新
                BeanUtil.copyProperties(orderBasicDto, odsOrder, CopyOptions.create().setIgnoreNullValue(true));
                BeanUtil.copyProperties(recipientDto, odsOrder, CopyOptions.create().setIgnoreNullValue(true));

                //if (payType == 0) {  // 只有当原有支付方式为货到付款时，当改成在线支付时，在支付成功后进行更新
                    odsOrder.setPayType(payType);
               // }
                //当支付类型为 货到付款时 订单状态改为已确认
                if (orderBasicDto.getPayType() == 0 || orderBasicDto.getPayType().toString().equals("4") || orderBasicDto.getPayType().toString().equals("5") ) {
                    odsOrder.setOrderStatus((byte) 1);
                }

                if (orderBasicDto.getPayType().toString().equals("4") || orderBasicDto.getPayType().toString().equals("5")){
                    odsOrder.setPayStatus((byte) 1);
                }

                //修改订单
                super.update(odsOrder);

                if (PublicUtil.isEmpty(strOrderIds)) {
                    strOrderIds = odsOrder.getOrderId().toString();
                } else {
                    strOrderIds += "," + odsOrder.getOrderId().toString();
                }
                totalPay += odsOrder.getAmountPayable();
            }//end if
            //兑奖商品处理
            odsAwardRecordService.getAwardRecordList(orderBasicDto);

            mapResult.put("pay_order_ids", strOrderIds);
            mapResult.put("totalpay", totalPay.toString());
        }//for orderBasicDtos


        //订单商品list>0
        if (listBookStock.size() > 0) {
            // mod by wg 20190727 判断是否为用户订单

            if (isUserOrder) {
                //预定仓库货物
                bookProductAndTimeout(listBookStock, "yes", payType,strOrderIds);
            } else {
                //预定仓库货物
                bookProductAndTimeout(listBookStock, "no", payType,strOrderIds);
            }


            // add by wg 20190605 秒杀商品库存锁定
            if (cmsSecKillSkuDtos != null && cmsSecKillSkuDtos.size() > 0) {
                cmcFeignApi.updateSecKillSkusCount(cmsSecKillSkuDtos);
            }
        }

        return mapResult;
    }

    /**
     * 预定仓库货物,和订单支付计时(redis过期事件)
     *
     * @param listBookStock
     */
    private void bookProductAndTimeout(List<Map> listBookStock, String s, Byte payType,String strOrderIds) {
//s区分是用户发货，还是店铺发货，店铺发货则店铺货物不用减少
        String s3z = JSON.toJSONString(listBookStock);

//库存减少,店铺对应的库存也要减少,no的时候店铺需要发货，店铺的库存没有变化
        //todo feign s
        Wrapper result = wmcStorageFeignApi.preadd(s3z);  // 锁定库存
        /**
         * 进行redis定时任务，当支付状态为“未支付”时，订单状态变为取消，同时返库存
         * 货到付款和线下手工单，不进行redis定时任务
         */
        if (payType != 0 && payType != 8) {  // 只对线上支付方式进行redis定时任务
            if (result != null && result.getCode() == 200) {
                if (s.equals("yes")) {  // 用户订单

                    if (strOrderIds!=null){
                        String[] split = strOrderIds.split(",");
                        for (int i = 0; i < split.length; i++) {
                            String id = "zero:" + split[i];
                            System.out.println("redis存入的key："+id);
                            redisTemplate.opsForValue().set(id, "订单", Quartz.second, TimeUnit.SECONDS);
                        }
                    }

                } else { // 店铺进货单

                    if (strOrderIds!=null){
                        String[] split = strOrderIds.split(",");
                        for (int i = 0; i < split.length; i++) {
                            String id = "first:" + split[i];
                            redisTemplate.opsForValue().set(id, "订单", Quartz.second, TimeUnit.SECONDS);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<OdsOrder> getCommissionOrders(Long shopId) {
        Example example = new Example(OdsOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("shopId", shopId);
        criteria.andEqualTo("orderType", (byte)1); // 消费者订单
        criteria.andEqualTo("isFactory", false); // todo 厂家直销订单是否有提现，暂时没有
        criteria.andEqualTo("commissionStatus", (byte)0);  // 还未申请提现的订单
        criteria.andNotEqualTo("shippingType", (byte)3); // 不是云顶店铺发货的订单
        criteria.andEqualTo("payStatus", true);  // 已付款的订单
        criteria.andIn("orderStatus", Arrays.asList((byte)2, (byte)5)); // 订单状态为部分退款和完成的订单
        criteria.andIn("shippingStatus", Arrays.asList((byte)2, (byte)3)); // 发货状态为已发货，或已收货的订单
        criteria.andCondition("DATEDIFF(NOW(),send_time)>=" + String.valueOf(Quartz.day)); // 发货时间大于7天的订单

        List<OdsOrder> odsOrders = odsOrderMapper.selectByExample(example);
        List<OdsOrder> listOrders = new ArrayList<>();

        for (OdsOrder odsOrder : odsOrders) {
            if (odsOrder.getOrderStatus().toString().equals("4") || odsOrder.getOrderStatus().toString().equals("5")) {
                Integer refundmoney=wmcStorageFeignApi.getrefundamound(odsOrder.getOrderId());
                if(refundmoney==null){
                    log.error("获取订单退货退款信息失败");
                    continue;
                }
                //部分退款，需要转账，订单总金额-已退款部分为最终结算的款
                odsOrder.setRefundMoney(refundmoney);
                listOrders.add(odsOrder);
            } else if (odsOrder.getOrderStatus().toString().equals("2")) {
                boolean flag = wmcStorageFeignApi.ifexits(odsOrder.getOrderId());
                if (!flag) {
                    //正常购买，不退款的
                    odsOrder.setRefundMoney(0);
                    listOrders.add(odsOrder);
                }
            }
        }

        return listOrders;
    }

    // 获取正在秒杀活动中的商品
    @Override
    public List<CmsSecKillSkuDto> getSecKillSkus() {
        Set<String> keys = redisTemplate.keys(RedisKeyUtil.getSecKillKeys());

        if (CollectionUtils.isEmpty(keys)) {
            return new ArrayList<>();
        }

        List<CmsSecKillSkuDto> cmsSecKillSkuDtoList = new ArrayList<>();
        Date now = new Date();
        for (String secKillKey : keys) {
            CmsSecKillDto cmsSecKillDto = (CmsSecKillDto)redisTemplate.opsForValue().get(secKillKey);
            if (cmsSecKillDto != null && cmsSecKillDto.getIsEnable() && now.getTime() >= cmsSecKillDto.getStartTime().getTime()
                    && now.getTime() <= cmsSecKillDto.getEndTime().getTime()) {
                Set<String> skuKeys = redisTemplate.keys(RedisKeyUtil.getSecKillSkuKeys(String.valueOf(cmsSecKillDto.getSecKillId())));

                for (String skuKey : skuKeys) {
                    CmsSecKillSkuDto cmsSecKillSkuDto = (CmsSecKillSkuDto)redisTemplate.opsForValue().get(skuKey);
                    if (cmsSecKillSkuDto != null) {
                        cmsSecKillSkuDtoList.add(cmsSecKillSkuDto);
                    }
                }
            }
        }

        return cmsSecKillSkuDtoList;
    }



    private void addOrderPoint(OdsOrder odsOrder){
        OdsPointsDto odsPointsDto = new OdsPointsDto();

        odsPointsDto.setOrderId(odsOrder.getOrderId().toString());
        odsPointsDto.setUserId(odsOrder.getUserId());
        odsPointsDto.setPointType((byte)1);//消费加积分

        if (odsOrder.getOrderType().toString().equals("2")){   //店铺下单

            odsPointsDto.setNumber(Math.round(odsOrder.getAmountPayable()/GlobalConstant.SHOP_POINT_RATE));
            odsPointsDto.setPointAspect((byte)2); //B端
        }else{

            odsPointsDto.setNumber(odsOrder.getAmountPayable());
            odsPointsDto.setPointAspect((byte)1);  //C端
        }


        odsPointsController.addSignIn(odsPointsDto);
    }

    @Override
    public Wrapper  reduceOrderPoint(OrderInfoDto orderInfoDto,String orderIds){

        OdsPoints odsPoints = odsPointsService.selectLastOneByUserId(orderInfoDto.getUserId());
        if (PublicUtil.isEmpty(odsPoints)){
            throw new OmcBizException(ErrorCodeEnum.OMC10031005);
        }

        Integer pointGoodsBalance = 0;
        List<OrderBasicDto> orderBasicDtos = orderInfoDto.getOrderBasicDtos();
        OrderBasicDto orderBasicDto = orderBasicDtos.get(0);
        pointGoodsBalance = orderBasicDto.getPointBalance();

        OdsPointsDto odsPointsDto = new OdsPointsDto();
        odsPointsDto.setNumber(pointGoodsBalance);
        odsPointsDto.setPointType((byte) 0);//消费
        odsPointsDto.setPointBalance(odsPoints.getPointBalance());
        odsPointsDto.setUserId(orderInfoDto.getUserId());
        odsPointsDto.setOrderId(orderIds);

        if (orderBasicDto.getOrderType().toString().equals("2")){   //店铺下单
            odsPointsDto.setPointAspect((byte)2); //B端

        }else{
            odsPointsDto.setPointAspect((byte)1);  //C端

        }

        Long num = odsPointsService.doPointUpdate(odsPointsDto);

        if (num > 0){
            return WrapMapper.ok(1);
        }else{
            return WrapMapper.error("操作失败");
        }
    }

    @Override
    public List<OdsOrder> search(JSONObject jsonObject){
        int page = 1;
        int size = 20;
        List<OdsOrder> list = new ArrayList<>();
        if (jsonObject.get("page") != null && jsonObject.get("size") != null) {
            page = Integer.valueOf(jsonObject.get("page").toString());
            size = Integer.valueOf(jsonObject.get("size").toString());
        }

        Example example = new Example(OdsOrder.class);
        example.setOrderByClause("create_time desc");//排序 降序
        Example.Criteria criteria = example.createCriteria();


        if ( jsonObject.get("warehouseId") != null ){
            Long warehouseId = Long.valueOf(jsonObject.get("warehouseId").toString());
            criteria.andEqualTo("warehouseId", warehouseId);
        }else if ( jsonObject.get("groupId") != null ){
            Long groupId = Long.parseLong(jsonObject.get("groupId").toString());
            List<WarehouseInfoDto> wmsWarehouseList = wmcStorageFeignApi.getWarehouseInfoByGroupId(groupId);
            List<Long> warehouseIdList = wmsWarehouseList.stream().map(WarehouseInfoDto::getWarehouseId).collect(Collectors.toList());

            if (warehouseIdList != null && warehouseIdList.size() > 0) {
                criteria.andIn("warehouseId", warehouseIdList);
            }
        }

        if (jsonObject.get("orderId") != null && !jsonObject.get("orderId").equals("")) {
            Long orderId = Long.valueOf(jsonObject.get("orderId").toString());
            criteria.andEqualTo("orderId", orderId);
        }

        if (jsonObject.get("userId") != null && !jsonObject.get("userId").equals("")) {
            Long userId = Long.valueOf(jsonObject.get("userId").toString());
            criteria.andEqualTo("userId", userId);
        }

        if (jsonObject.get("userName") != null && !jsonObject.get("userName").equals("")) {
            criteria.andLike("consignee", "%" + jsonObject.get("userName").toString() + "%");
        }

        if (jsonObject.get("shopName") != null && !jsonObject.get("shopName").equals("")) {
            List<Long> shopids = smcFeignApi.getShopIdsShopName(jsonObject.get("shopName").toString());
            if (shopids != null && shopids.size() != 0) {
                criteria.andIn("shopId", shopids);
            } else {
                return list;

            }

        }

        if (jsonObject.get("payType") != null && !jsonObject.get("payType").equals("")) {
            criteria.andEqualTo("payType", jsonObject.get("payType"));
        }

        if (jsonObject.get("payStatus") != null && !jsonObject.get("payStatus").equals("")) {
            criteria.andEqualTo("payStatus", jsonObject.get("payStatus"));
        }
        if (jsonObject.get("isCheckout") != null && !jsonObject.get("isCheckout").equals("")) {
            criteria.andEqualTo("isCheckout", jsonObject.get("isCheckout"));
        }
        if (jsonObject.get("orderStatus") != null && !jsonObject.get("orderStatus").equals("")) {
            criteria.andEqualTo("orderStatus", jsonObject.get("orderStatus"));
        }
        if (jsonObject.get("beginTime") != null && !jsonObject.get("beginTime").equals("")) {
            Object beginTime = jsonObject.get("beginTime");
            Object endTime = jsonObject.get("endTime");

            criteria.andLessThanOrEqualTo("createTime", endTime);
            criteria.andGreaterThan("createTime", beginTime);

        }

        if (jsonObject.get("orderType") != null && !jsonObject.get("orderType").equals("")) {
            criteria.andEqualTo("orderType", jsonObject.get("orderType"));
        }
        if (jsonObject.get("shippingStatus") != null && !jsonObject.get("shippingStatus").equals("")) {
            criteria.andEqualTo("shippingStatus", jsonObject.get("shippingStatus"));
        }
        PageHelper.startPage(page, size);
         list = odsOrderMapper.selectByExample(example);
        if (list == null && list.size() < 1) {
            return list;

        }



       List<Long> specIds =  list.stream().map(OdsOrder::getShopId).collect(Collectors.toList());

               //两次调用feign
        List<ShopInfoDto> shopname = smcFeignApi.getShopInfoByShopIds(specIds);
        if (shopname == null || shopname.size() < 1) {
            return list;
        }


        // todo 注意：如果数据库中有店铺删除掉，但订单中有该店铺时，warehouseName会出现越界错误
        for (OdsOrder odsOrder : list) {
            for (ShopInfoDto item : shopname) {
                if (odsOrder.getShopId().toString().equals(item.getShopId().toString())) {
                    odsOrder.setShopName(item.getShopName());

                }
            }
        }

        // add by wg 20190724 根据仓库ID获取真正的仓库信息，为兼容以前订单上述流程不更改
        List<Long> warehouseIds = list.stream().distinct().map(OdsOrder::getWarehouseId).collect(Collectors.toList());
        Wrapper retWrapper = wmcStorageFeignApi.getWarehouseInfo(warehouseIds);
        if (retWrapper == null || retWrapper.getCode() != 200) {
             return list;

        }

        List<WarehouseInfoDto> warehouseInfoDtos = (List<WarehouseInfoDto>) retWrapper.getResult();
        for (OdsOrder odsOrder : list) {
            for (WarehouseInfoDto warehouseInfoDto : warehouseInfoDtos) {
                if (odsOrder.getWarehouseId() != null &&
                        odsOrder.getWarehouseId().toString().equals(warehouseInfoDto.getWarehouseId().toString())) {
                    odsOrder.setWarehouseName(warehouseInfoDto.getWarehouseName());
                    odsOrder.setWarehouseId(warehouseInfoDto.getWarehouseId());
                    break;
                }
            }
        }


        return list;

    }

    @Override
    public   List<OrderGoodsDto> getWmsGiftList(List<OrderGoodsDto> cmsSpecOrderDtos, Long shopId,Byte orderType){
        List<OrderGoodsDto> cmsSpecDtoList = new ArrayList<>();
        WmsGiftDto wmsGiftDto = new WmsGiftDto();
        wmsGiftDto.setShopId(shopId);
        wmsGiftDto.setGiftType(orderType);
        List<WmsGiftDto> wmsGiftDtoList  = wmcStorageFeignApi.getGiftList(wmsGiftDto);
        if (cmsSpecOrderDtos!=null && cmsSpecOrderDtos.size()>0){
            for (OrderGoodsDto orderSpec : cmsSpecOrderDtos){
                for (WmsGiftDto item : wmsGiftDtoList){
                    if (orderSpec.getSpecId().equals(item.getSpecId())) {
                        int num = 0;
                        //1.是否达到购买数量
                        if (item.getNumber() > 0 && orderSpec.getGoodsNum() <  item.getNumber()) {
                            break;
                        }
                        //2.是否达到购买金额
                        if (item.getFee() > 0 && orderSpec.getGoodsNum() * orderSpec.getGoodsPrice() < item.getFee()){
                            break;
                        }

                        //3.计算出库数量
                        if (item.getNumber() > 0){
                            num = (int)Math.floor(orderSpec.getGoodsNum()/item.getNumber());
                        }

                        //4.赠品是否还有库存
                        if (item.getStockNumber() - item.getOutNumber() < item.getGiftNum() * num){
                            break;
                        }
                        OrderGoodsDto cmsSpecDto = new OrderGoodsDto();
                        cmsSpecDto.setSpecName(item.getSpecName());
                        if (num > 0){
                            cmsSpecDto.setGoodsNum(item.getGiftNum() * num);
                            wmsGiftDto.setOutNumber(item.getGiftNum() * num);
                        }

                        cmsSpecDto.setSpecId(item.getGiftSpecId());
                        cmsSpecDto.setGoodsWeight(item.getWeight());
                        cmsSpecDto.setGoodsPrice(0);
                        cmsSpecDto.setGoodsStatus((byte)4);
                        cmsSpecDtoList.add(cmsSpecDto);

                        break;
                    }

                }//for

            }//for
        }

        return cmsSpecDtoList;
    }

    //    @Override
//    public List<OdsOrderApiDto> getOrderInformation(OdsOrderApiDto orderShopDto) {
//        return odsOrderMapper.getOrderInformations(orderShopDto);
//    }
    @Override
    public List<OrderShopDto> getOrderInformation(OrderShopDto orderShopDto) {

        //查询订单表相关信息

        List<OrderShopDto> list1 = odsOrderMapper.getOrderInformation(orderShopDto);

        List<Long> orderShopId = list1.stream().map(OrderShopDto::getShopId).collect(Collectors.toList());

        List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopInfoByShopIds(orderShopId);

        for (ShopInfoDto shopInfoByShopId : shopInfoByShopIds) {
            for (OrderShopDto shopDto : list1) {
                if (shopDto.getShopId().equals(shopInfoByShopId.getShopId())){
                    BeanUtils.copyProperties(shopInfoByShopId,shopDto);
                }
            }
        }
        return list1;
    }

    @Override
    public PageInfo<OrderShopDto> findDescShop(Date beginTimeDate, Integer page, Integer size) {

        String beginTime= DateUtil.getStringDate(beginTimeDate);
        String sendTime = beginTime;

        long endTimeLong = DateUtil.dayTimeInMillis();
        Date endTimeDate = new Date(endTimeLong);
        String endTime = DateUtil.getStringDate(endTimeDate);

        int num = (int) ((endTimeDate.getTime()-beginTimeDate.getTime())/(3600*24*1000));

        Calendar ca = Calendar.getInstance();
        // num为天数，可以改变的
        ca.setTime(beginTimeDate);
        ca.add(Calendar.DATE, -num);
        Date sbeginTimeDate = ca.getTime();
        String sbeginTime = DateUtil.getStringDate(sbeginTimeDate);

        OrderShopDto orderShopDto1 = new OrderShopDto();
        orderShopDto1.setBeginTime(sbeginTime);
        orderShopDto1.setEndTime(sendTime);
        List<OrderShopDto> shopDtoList1= odsOrderMapper.findCountMoney(orderShopDto1);

        OrderShopDto orderShopDto2 = new OrderShopDto();
        orderShopDto2.setBeginTime(beginTime);
        orderShopDto2.setEndTime(endTime);
        List<OrderShopDto> shopDtoList2= odsOrderMapper.findCountMoney(orderShopDto2);

        List<OrderShopDto> shopDtoList = new ArrayList<>();

        List<OrderShopDto> list = new ArrayList<>();

        List<Long> shopIdList1 = shopDtoList1.stream().map(OrderShopDto::getShopId).distinct().collect(Collectors.toList());

        //for (Long shopId1 : shopIdList1) {
        //    if (shopIdList2.contains(shopId1)){
        //        continue;
        //    }else{
        //        shopNoOrder.add(shopId1);
        //    }
        //}

        HashMap<Long, OrderShopDto> hashMap = new HashMap<>();

        HashMap<Long, OrderShopDto> listMap = new HashMap<>();

        shopDtoList2.forEach(e-> hashMap.put(e.getShopId(),e));

        //循环遍历shopDtoList1,即第一段时间内所有的店铺
        for (OrderShopDto orderShopDto : shopDtoList1) {
            //如果第二段时间该店铺不存在即为没下过单,则把该店铺保存shopDtoList
            if (hashMap.get(orderShopDto.getShopId())==null) {
                shopDtoList.add(orderShopDto);
            }
            //如果第二段时间下单金额变少,则保存该店铺到shopDtoList
            for (OrderShopDto shopDto : shopDtoList2) {
                if (orderShopDto.getShopId().equals(shopDto.getShopId())){
                    if (orderShopDto.getMaxPrice()/shopDto.getMaxPrice()>=2){
                        orderShopDto.setMinPrice(shopDto.getMaxPrice());
                        shopDtoList.add(orderShopDto);
                    }
                }
            }
        }

        shopDtoList.forEach(e-> listMap.put(e.getShopId(),e));

        List<Long> shopIdList = shopDtoList.stream().map(OrderShopDto::getShopId).distinct().collect(Collectors.toList());

        PageInfo<OrderShopDto> pageInfo = new PageInfo<>();

        if (page!=0&&size!=0&&page!=null&&size!=null){

            shopIdList = shopIdList1.stream().skip((page - 1) * size)
                    .limit(size)
                    .collect(Collectors.toList());
        }

        List<ShopInfoDto> shopInfoByShopIds = smcFeignApi.getShopInfoByShopIds(shopIdList);

        for (ShopInfoDto shopInfoByShopId : shopInfoByShopIds) {
            OrderShopDto needShopDto = listMap.get(shopInfoByShopId.getShopId());
            if(needShopDto!=null)
            {
                needShopDto.setShopName(shopInfoByShopId.getShopName());
                needShopDto.setRegionProvinceId(shopInfoByShopId.getRegionProvinceId());
                needShopDto.setRegionCityId(shopInfoByShopId.getRegionCityId());
                needShopDto.setRegionCountyId(shopInfoByShopId.getRegionCountyId());
                needShopDto.setAddress(shopInfoByShopId.getAddress());
                needShopDto.setTelephone(shopInfoByShopId.getTelephone());
                list.add(needShopDto);
            }
            System.out.println("shopInfoByShopId.getShopId()--------"+shopInfoByShopId.getShopId());

        }
        pageInfo.setList(list);

        pageInfo.setTotal(shopDtoList.size());

        return pageInfo;
    }

//店铺尾单
    @Override
    public PageInfo<OdsOrderApiDto> getLastOrder(Integer page, Integer size) {


        //查询第一阶段下单的店铺
        List<OdsOrder> odsOrders = odsOrderMapper.selectAll();

        List<Long> shopIdList = odsOrders.stream().map(OdsOrder::getShopId).distinct().collect(Collectors.toList());

        List<ShopInfoDto> allShopList = smcFeignApi.getShopInfoByShopIds(shopIdList);

        List<OdsOrderApiDto> list = new ArrayList<>();

        PageHelper.startPage(page, size);

        List<OdsOrderApiDto> orderShopDtos1 = odsOrderMapper.getLastOrderByShopIds(shopIdList);

        PageInfo<OdsOrderApiDto> pageInfo = new PageInfo(orderShopDtos1);

        List<OdsOrderApiDto> orderShopDtos = pageInfo.getList();


        for (OdsOrderApiDto orderShopDto : orderShopDtos) {
            for (ShopInfoDto shopInfo : allShopList) {
                if (orderShopDto.getShopId().equals(shopInfo.getShopId())) {
                    orderShopDto.setShopName(shopInfo.getShopName());
                    orderShopDto.setRegionProvinceId(shopInfo.getRegionProvinceId());
                    orderShopDto.setRegionCityId(shopInfo.getRegionCityId());
                    orderShopDto.setRegionCountyId(shopInfo.getRegionCountyId());
                    orderShopDto.setAddress(shopInfo.getAddress());
                    orderShopDto.setTelephone(shopInfo.getTelephone());
                    list.add(orderShopDto);
            }
            }
        }

        pageInfo.setList(list);

        return pageInfo;
    }

    @Override
    public PageInfo<ShopInfoDto> findNoOrderShop(Integer page, Integer size) {

        List<OdsOrder> odsOrders = odsOrderMapper.selectAll();

        List<ShopInfoDto> allShopInfo = smcFeignApi.getAllShopInfo();

        List<Long> shopIdList = odsOrders.stream().map(OdsOrder::getShopId).distinct().collect(Collectors.toList());


        List<Long> allShopIdList = allShopInfo.stream().map(ShopInfoDto::getShopId).distinct().collect(Collectors.toList());


        allShopIdList.remove(shopIdList);



        PageInfo<ShopInfoDto> list = new PageInfo<>();

        if (page==0&&size==0){

            List<ShopInfoDto> shopInfoDtoList = smcFeignApi.getShopInfoByShopIds(allShopIdList);

            list.setList(shopInfoDtoList);

            list.setTotal(allShopIdList.size());

            //return list;
        }else {

            allShopIdList = allShopIdList.stream().skip((page - 1) * size)
                    .limit(size)
                    .collect(Collectors.toList());

            List<ShopInfoDto> shopInfoDtoList = smcFeignApi.getShopInfoByShopIds(allShopIdList);

            list.setList(shopInfoDtoList);

            list.setTotal(allShopIdList.size());
        }
        return  list;
    }

    @Override
    public List<OdsOrderApiDto> countByShopIds(List<Long> shopIdList,String beginTime,String endTime) {

        if (shopIdList!=null&&shopIdList.size()>0) {

            List<OdsOrderApiDto> list = odsOrderMapper.countByShopIds(shopIdList, beginTime, endTime);

            List<Long> shopList = list.stream().map(OdsOrderApiDto::getShopId).collect(Collectors.toList());

            List<ShopInfoDto> shopInfo = smcFeignApi.getShopInfoByShopIds(shopList);

            if (shopList != null || shopIdList.size() > 0 || shopInfo != null || shopInfo.size() > 0) {
                for (OdsOrderApiDto orderShopDto : list) {
                    for (ShopInfoDto shopInfoByShopId : shopInfo) {
                        if (orderShopDto.getShopId().equals(shopInfoByShopId.getShopId())) {
                            BeanUtils.copyProperties(shopInfoByShopId, orderShopDto);
                        }
                    }
                }
            }
            return list;
        }
        return null;
    }

    @Override
    public Map countOrderByShopIds(List<Long> shopIds, Date beginTime, Date endTime){

        Map map = new HashMap();
        Long orderCount = 0L;
        Long amountPayable = 0L;

        List<OdsOrderApiDto> list = odsOrderMapper.countByShopIds(shopIds,beginTime,endTime);

        if (list != null && list.size() > 0){

            for (OdsOrderApiDto dto : list){
                orderCount += dto.getOrderCount();
                amountPayable += dto.getAmountPayable();
            }

        }
        map.put("orderCount",orderCount);
        map.put("amountPayable",amountPayable);

        return map;
    }

    @Override
    public List<DmsStoreOrderApi> countByDmsStore(List<DmsStoreOrderApi> dmsStoreOrderApis) {

        List<DmsStoreOrderApi> list = odsOrderMapper.countByDmsStore(dmsStoreOrderApis);

        return list;
    }

    @Override
    public List<ShopOrderGoodsDto> findOrderGoods(ShopOrderGoodsDto shopOrderGoodsDto) {

        List<ShopOrderGoodsDto> list = odsOrderMapper.findOrderGoods(shopOrderGoodsDto);


        List<Long> specList = list.stream().map(ShopOrderGoodsDto::getSpecId).collect(Collectors.toList());

        List<ProdSpecApiDto> specNameBySpecId = pmcFeignApi.getSpecNameBySpecIds(specList);
        System.out.println(specNameBySpecId);
        for (ShopOrderGoodsDto orderGoodsDto : list) {
            for (ProdSpecApiDto prodSpecApiDto : specNameBySpecId) {
                if (orderGoodsDto.getSpecId().equals(prodSpecApiDto.getSpecId())){
                    orderGoodsDto.setSpecName(prodSpecApiDto.getSpecName());
                }
            }
        }
        return list;
    }

    @Override
    public List<StoreOrderDto> countByShopList(List<StoreOrderDto> storeOrderDtos) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime = formatter.format(DateUtil.monthTimeBegin());
        String endTime = formatter.format(DateUtil.monthTimeEnd());
        List<StoreOrderDto> list = new ArrayList<>();
        System.out.println(list.size());
        for (StoreOrderDto storeOrderDto : storeOrderDtos) {
            StoreOrderDto dto = odsOrderMapper.countByShopList(storeOrderDto,beginTime,endTime);
            list.add(dto);
        }

        return list;
    }
}
